


// jQuery(window).load(function() {
//
//     "use strict";
//
//     // Page Preloader
//     jQuery('#preloader').delay(350).fadeOut(function(){
//         jQuery('body').delay(350).css({'overflow':'visible'});
//     });
// });

jQuery(document).ready(function() {
    // $('#preloader').delay(350).fadeOut();
    "use strict";

    var browserIdentify =function () {
        var browser = {
            versions: function () {
                var u = navigator.userAgent, app = navigator.appVersion;
                return {         //移动终端浏览器版本信息
                    trident: u.indexOf('Trident') > -1, //IE内核
                    presto: u.indexOf('Presto') > -1, //opera内核
                    webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
                    gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
                    mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
                    ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
                    android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或uc浏览器
                    iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
                    iPad: u.indexOf('iPad') > -1, //是否iPad
                    webApp: u.indexOf('Safari') == -1 //是否web应该程序，没有头部与底部
                };
            }(),
            language: (navigator.browserLanguage || navigator.language).toLowerCase()
        }

        if (browser.versions.mobile) {//判断是否是移动设备打开。browser代码在下面
            var ua = navigator.userAgent.toLowerCase();//获取判断用的对象
            /*if (ua.match(/MicroMessenger/i) == "micromessenger") {

            }*/
            // $("#mobilelogout").show()
            $("#overview , #member ,#bonus,#dividend,#finance,#system,#menutoggle,#pclogout,#verification").show()
        } else {
            $("#overview , #member ,#bonus,#dividend,#finance,#system,#menutoggle,#pclogout,#verification").show()

            if(browser.versions.trident){
                $.rootErrorDialog("您的浏览器不兼容,请安装火狐浏览器",2000,function () {
                    window.location.href="/admin/404.html"
                });
            }
        }
    }

    browserIdentify()



    // Toggle Left Menu
    jQuery('.leftpanel .nav-parent > a').on('click', function() {

        var parent = jQuery(this).parent();
        var sub = parent.find('> ul');
        // Dropdown works only when leftpanel is not collapsed
        if(!jQuery('body').hasClass('leftpanel-collapsed')) {
            if(sub.is(':visible')) {
                sub.slideUp(200, function(){
                    parent.removeClass('nav-active');
                    jQuery('.mainpanel').css({height: ''});
                    adjustmainpanelheight();
                });
            } else {
                // closeVisibleSubMenu(parent.siblings(".nav-parent"));
                parent.addClass(' nav-active ');
                sub.slideDown(200, function(){
                    adjustmainpanelheight();
                });
            }
        }
        return false;
    });



    function adjustmainpanelheight() {
        // Adjust mainpanel height
        var docHeight = jQuery(document).height();
        if(docHeight > jQuery('.mainpanel').height())
            jQuery('.mainpanel').height(docHeight);
    }
    adjustmainpanelheight();

// Tooltip
    jQuery('.tooltips').tooltip({ container: 'body'});

    // Popover
    jQuery('.popovers').popover();

    // Close Button in Panels
    jQuery('.panel .panel-close').click(function(){
        jQuery(this).closest('.panel').fadeOut(200);
        return false;
    });



    // Add class everytime a mouse pointer hover over it
    jQuery('.nav-bracket > li').hover(function(){
        jQuery(this).addClass('nav-hover');
    }, function(){
        jQuery(this).removeClass('nav-hover');
    });


    // Menu Toggle
    jQuery('.menutoggle').click(function(){

        var body = jQuery('body');
        var bodypos = body.css('position');

        if(bodypos != 'relative') {

            if(!body.hasClass('leftpanel-collapsed')) {
                body.addClass('leftpanel-collapsed');
                jQuery('.nav-bracket ul').attr('style','');

                jQuery(this).addClass('menu-collapsed');

            } else {
                body.removeClass('leftpanel-collapsed chat-view');
                jQuery('.nav-bracket li.active ul').css({display: 'block'});

                jQuery(this).removeClass('menu-collapsed');

            }
        } else {

            if(body.hasClass('leftpanel-show'))
                body.removeClass('leftpanel-show');
            else
                body.addClass('leftpanel-show');

            adjustmainpanelheight();
        }

    });



    reposition_topnav();

    jQuery(window).resize(function(){

        if(jQuery('body').css('position') == 'relative') {

            jQuery('body').removeClass('leftpanel-collapsed chat-view');

        } else {

            jQuery('body').removeClass('chat-relative-view');
            jQuery('body').css({left: '', marginRight: ''});
        }


        reposition_topnav();

    });






    /* This function allows top navigation menu to move to left navigation menu
     * when viewed in screens lower than 1024px and will move it back when viewed
     * higher than 1024px
     */
    function reposition_topnav() {
        if(jQuery('.nav-horizontal').length > 0) {

            // top navigation move to left nav
            // .nav-horizontal will set position to relative when viewed in screen below 1024
            if(jQuery('.nav-horizontal').css('position') == 'relative') {

                if(jQuery('.leftpanel .nav-bracket').length == 2) {
                    jQuery('.nav-horizontal').insertAfter('.nav-bracket:eq(1)');
                } else {
                    // only add to bottom if .nav-horizontal is not yet in the left panel
                    if(jQuery('.leftpanel .nav-horizontal').length == 0)
                        jQuery('.nav-horizontal').appendTo('.leftpanelinner');
                }

                jQuery('.nav-horizontal').css({display: 'block'})
                    .addClass('nav-pills nav-stacked nav-bracket');

                jQuery('.nav-horizontal .children').removeClass('dropdown-menu');
                jQuery('.nav-horizontal > li').each(function() {

                    jQuery(this).removeClass('open');
                    jQuery(this).find('a').removeAttr('class');
                    jQuery(this).find('a').removeAttr('data-toggle');

                });

                if(jQuery('.nav-horizontal li:last-child').has('form')) {
                    jQuery('.nav-horizontal li:last-child form').addClass('searchform').appendTo('.topnav');
                    jQuery('.nav-horizontal li:last-child').hide();
                }

            } else {
                // move nav only when .nav-horizontal is currently from leftpanel
                // that is viewed from screen size above 1024
                if(jQuery('.leftpanel .nav-horizontal').length > 0) {

                    jQuery('.nav-horizontal').removeClass('nav-pills nav-stacked nav-bracket')
                        .appendTo('.topnav');
                    jQuery('.nav-horizontal .children').addClass('dropdown-menu').removeAttr('style');
                    jQuery('.nav-horizontal li:last-child').show();
                    jQuery('.searchform').removeClass('searchform').appendTo('.nav-horizontal li:last-child .dropdown-menu');
                    jQuery('.nav-horizontal > li > a').each(function() {

                        jQuery(this).parent().removeClass('nav-active');

                        if(jQuery(this).parent().find('.dropdown-menu').length > 0) {
                            jQuery(this).attr('class','dropdown-toggle');
                            jQuery(this).attr('data-toggle','dropdown');
                        }

                    });
                }

            }

        }
    }


    // Sticky Header
    if(jQuery.cookie('sticky-header'))
        jQuery('body').addClass('stickyheader');

    // Sticky Left Panel
    if(jQuery.cookie('sticky-leftpanel')) {
        jQuery('body').addClass('stickyheader');
        jQuery('.leftpanel').addClass('sticky-leftpanel');
    }

    // Left Panel Collapsed
    if(jQuery.cookie('leftpanel-collapsed')) {
        jQuery('body').addClass('leftpanel-collapsed');
        jQuery('.menutoggle').addClass('menu-collapsed');
    }



    // Check if leftpanel is collapsed
    if(jQuery('body').hasClass('leftpanel-collapsed'))
        jQuery('.nav-bracket .children').css({display: ''});


    // Handles form inside of dropdown
    jQuery('.dropdown-menu').find('form').click(function (e) {
        e.stopPropagation();
    });



    var gparam={
        hash:'/'
    }



    var routeBefore=function(a){

        var _routeHash = location.hash.replace("#","")

        // console.log(_routeHash)
        gparam.hash=_routeHash;
        $('#main-menu .nav-parent').removeClass("nav-active").find(".children").hide().find("li").removeClass("active")

        $('#main-menu a[href="#'+ _routeHash +'"]').parent("li")
            .addClass("active").parent(".children").show().parents(".nav-parent").addClass("nav-active")

    };
    var doGetUser = function (authority,callback) {
        var rootUser=$("#root-user");

        $.restPost("/user/doGetUserInfo",{token:window.localStorage.getItem('token')}).done(function (msg,data) {
            //记录登录 包括权限
            rootUser.text(data.nickName);


            window.localStorage.setItem('user',JSON.stringify(data))

            callback(4)
        })
            .fail(function (msg,data) {
                window.location.href="/admin/login_page.html"
            })
    };

    var injectTpl = function (tpl,title) {
        console.log(tpl)
        var $contentpanel=$("#contentpanel");
        var $titleTag=$("#title-tag");
        doGetUser(4,function (authority) {
            $.get(tpl,function (res) {

                $titleTag.text(title);
                $contentpanel.html(res)
                $("body").removeClass("leftpanel-show")
                $('#preloader').delay(350).fadeOut();
            })
        })
    };








    var to404=function () {
        // alert("to404")
        window.location.href="/admin/404.html"
    };






    //退出
    var logout = function () {
        $.restPost("/user/doLogout",{
            token:window.localStorage.getItem('token'),
        }).done(function (msg,data) {
            window.location.href="/admin/login_page.html"
        }).fail(function (msg,data) {
            //跳回登录界面
           alert("注销失败")
        })
    };
    $("#logout , #mobilelogout").on("click",function () {
        logout()
    });
   function routesMapInit() {
       var nd= $.now()

       var routes = {
           //会员管理
           '/member/manage':function () { injectTpl('/admin/member/manage.html','会员管理') },
           '/member/address/:id':function () { injectTpl('/admin/member/address.html','地址') },
           '/member/ticketmanage':function () { injectTpl('/admin/member/ticketmanage.html','优惠券管理') },
           '/member/ticketadd':function () { injectTpl('/admin/member/ticketedit.html','新增优惠券') },
           '/member/ticketedit/:id':function () { injectTpl('/admin/member/ticketedit.html','修改优惠券') },

           //产品管理
           '/product/manage':function () {injectTpl('/admin/product/manage.html','产品管理') },
           '/product/add':function () {injectTpl('/admin/product/edit.html','产品新增') },
           '/product/edit/:id':function () {injectTpl('/admin/product/edit.html','产品查看编辑') },

           '/product/managetype':function () {injectTpl('/admin/product/managetype.html','产品类别管理') },
           '/product/typeedit/:id':function () {injectTpl('/admin/product/typeedit.html','产品类别编辑') },
           '/product/typeadd':function () {injectTpl('/admin/product/typeedit.html','产品类别新增') },

           //广告图管理
           '/banner/manage':function () { injectTpl('/admin/banner/manage.html','广告图管理') },
           '/banner/edit/:id':function () { injectTpl('/admin/banner/edit.html','广告图修改') },
           '/banner/add':function () { injectTpl('/admin/banner/edit.html','广告图新增') },

           //订单
           '/order/manage':function () {injectTpl('/admin/order/manage.html','订单管理')}

       };

       var router = Router(routes).configure({
           before:routeBefore
       });
       router.init();

   }
    routesMapInit()

    // routesMap()






});

